package com.mes.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.github.pagehelper.PageInfo;
import com.mes.common.core.domain.BaseEntity;
import com.mes.common.core.domain.entity.SysDept;
import com.mes.common.core.domain.entity.SysRole;
import com.mes.common.core.domain.entity.SysUser;
import com.mes.common.core.service.BaseServiceImpl;
import com.mes.common.exception.SysException;
import com.mes.common.utils.SecurityUtils;
import com.mes.framework.cache.ConfigUtils;
import com.mes.system.domain.*;
import com.mes.system.mapper.*;
import com.mes.system.service.ISysRoleService;
import com.mes.system.service.ISysUserService;
import com.mes.system.service.SysTenantService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 租户Service业务层处理
 * @author hwg
 * @email hwg
 * @date 2023-03-25
 */
@Service
@Transactional(readOnly = true)
public class SysTenantServiceImpl extends BaseServiceImpl<SysTenantMapper, SysTenant> implements SysTenantService {

    private static final Logger log = LoggerFactory.getLogger(SysTenantServiceImpl.class);
    @Autowired
    private ISysRoleService sysRoleService;
    @Resource
    private SysTenantInitMenuMapper sysTenantInitMenuMapper;
    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private SysAutoCodeRuleMapper sysAutoCodeRuleMapper;
    @Resource
    private SysAutoCodePartMapper sysAutoCodePartMapper;

    /**
     * 获取单条数据
     * @param sysTenant 租户
     * @return 租户
     */
    @Override
    public SysTenant get(SysTenant sysTenant) {
        SysTenant dto = super.get(sysTenant);
        return dto;
    }

    /**
     * 获取单条数据
     * @param id 租户id
     * @return 租户
     */
    @Override
    public SysTenant get(String id) {
        SysTenant dto = super.get(id);
        return dto;
    }

    /**
     * 查询租户列表
     * @param sysTenant 租户
     * @return 租户
     */
    @Override
    public List<SysTenant> findList(SysTenant sysTenant) {
		List<SysTenant> sysTenantList = super.findList(sysTenant);
        return sysTenantList;
    }

    /**
     * 分页查询租户列表
     * @param sysTenant 租户
     * @return 租户
     */
    @Override
    public PageInfo<SysTenant> findPage(SysTenant sysTenant) {
		PageInfo<SysTenant> page = super.findPage(sysTenant);
        return page;
    }

    /**
     * 保存租户
     * @param sysTenant
     * @return 结果
     */
    @Override
    public boolean save(SysTenant sysTenant) {
        return super.save(sysTenant);
    }

    /**
     * 更新租户状态
     * @param sysTenant
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int updateStatus(SysTenant sysTenant) {
        return mapper.updateStatus(sysTenant);
    }

    /**
     * 删除租户信息
     * @param sysTenant
     * @return 结果
     */
    @Override
    public boolean remove(SysTenant sysTenant) {
        return super.remove(sysTenant);
    }

    /**
     * 批量删除租户
     * @param ids 需要删除的租户ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteSysTenantByIds(String[] ids) {
        return mapper.deleteSysTenantByIds(ids, BaseEntity.DEL_FLAG_DELETE);
    }

    @Override
    public SysTenant getByName(String tenantName) {
       return mapper.getByName(tenantName);
    }

    @Override
    @Transactional
    public boolean create(SysTenant sysTenant) {
        SysTenant existTenant = getByName(sysTenant.getTenantName());
        if(existTenant!=null) {
            throw new SysException("租户名称已存在");
        }
        boolean result = this.save(sysTenant);
        if(result) {
            //初始化租户数据
            //初始化角色
            SysRole sysRole = new SysRole();
            sysRole.setRoleName("管理员");
            sysRole.setRoleKey("admin");
            sysRole.setDataScope("2");
            sysRole.setMenuCheckStrictly(true);
            sysRole.setDeptCheckStrictly(true);
            sysRole.setTenantId(sysTenant.getId());
            sysRole.setSort("1");
            sysRole.setStatus("0");
            sysRoleService.save(sysRole);
            //保存角色菜单权限
            List<SysTenantInitMenu> sysTenantInitMenuList = sysTenantInitMenuMapper.findList(null);
            List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
            for(SysTenantInitMenu sysTenantInitMenu:sysTenantInitMenuList) {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(sysRole.getId());
                sysRoleMenu.setMenuId(sysTenantInitMenu.getMenuId());
                sysRoleMenus.add(sysRoleMenu);
            }
            sysRoleMenuMapper.batchRoleMenu(sysRoleMenus);
            //创建用户
            SysUser sysUser = new SysUser();
            sysUser.setTenantId(sysTenant.getId());
            sysUser.setUserName("admin");
            sysUser.setNickName("管理员");
            sysUser.setName("管理员");
            String password = ConfigUtils.getConfigValueByKey("sys.user.initPassword","123456");
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            sysUserService.save(sysUser);
            //添加用户角色关联
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(sysRole.getId());
            sysUserRole.setUserId(sysUser.getId());
            List<SysUserRole> sysUserRoles = new ArrayList<>();
            sysUserRoles.add(sysUserRole);
            sysUserRoleMapper.batchUserRole(sysUserRoles);
            //创建顶级部门
            SysDept sysDept = new SysDept();
            sysDept.setDeptCode("100");
            sysDept.setTenantId(sysTenant.getId());
            sysDept.setDeptName(sysTenant.getTenantName());
            sysDept.setDeptFullName(sysTenant.getTenantName());
            sysDept.setDeptType("org");
            sysDept.setDeptPinyin(PinyinUtil.getPinyin("测试","")+","+PinyinUtil.getFirstLetter("测试",""));
            sysDept.setParentId("0");
            sysDept.setParentIds("100");
            sysDept.setTreeSort(100);
            sysDept.setTreeSorts("000010");
            sysDept.setTreeLevel(1);
            sysDept.setTreeLeaf("n");
            sysDept.preInsert();
            sysDeptMapper.insert(sysDept);

            //初始化编码
            List<SysAutoCodeRule> ruleList = sysAutoCodeRuleMapper.findList(new SysAutoCodeRule());
            for(SysAutoCodeRule sysAutoCodeRule:ruleList) {
                SysAutoCodeRule newRule = new SysAutoCodeRule();
                BeanUtil.copyProperties(sysAutoCodeRule,newRule);
                newRule.setTenantId(sysTenant.getId());
                newRule.setId(null);
                newRule.preInsert();
                sysAutoCodeRuleMapper.insert(newRule);
                //查询明细
                SysAutoCodePart paramPart = new SysAutoCodePart();
                paramPart.setRuleId(sysAutoCodeRule.getId());
                List<SysAutoCodePart> partList = sysAutoCodePartMapper.findList(paramPart);
                for(SysAutoCodePart sysAutoCodePart:partList) {
                    SysAutoCodePart newPart = new SysAutoCodePart();
                    BeanUtil.copyProperties(sysAutoCodePart,newPart);
                    newPart.setTenantId(sysTenant.getId());
                    newPart.setRuleId(newRule.getId());
                    newPart.setId(null);
                    newPart.preInsert();
                    sysAutoCodePartMapper.insert(newPart);
                }
            }
        }
        return  result;
    }

}
